package com.gopay.bis.service.bank.impl.ebank;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;

import com.gopay.bis.common.util.BankLogUtils;
import com.gopay.bis.common.util.BisPayCheckUtils;
import com.gopay.bis.common.util.constants.BisPayConstants;
import com.gopay.bis.manager.bank.ebank.AbcB2bManager;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.AbcConstants;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.abc.ebank.AbcB2bMessage;
import com.gopay.common.exception.GopayException;
import com.gopay.remote.bank.BankInteractRemoteService;

/**
 * 农行网银B2B实现
 * 
 * @AbcB2bBankServiceImpl.java
 * @author LiLiLi
 * 
 */
public class AbcB2bBankServiceImpl implements BankInteractRemoteService {

	@Resource(name = "abcB2bManager")
	private AbcB2bManager abcB2bManager;

	public Result pay(BaseMessage base) {
		Result result = new Result(false);
		try {
			AbcB2bMessage messageB2B = new AbcB2bMessage();
			BeanUtils.copyProperties(base, messageB2B);
			messageB2B = (AbcB2bMessage) abcB2bManager.sign(messageB2B);
			result.setDefaultModel(messageB2B);
			result.setSuccess(true);
		} catch (GopayException e) {
			BankLogUtils.printServiceImplExceptionLog(e);
			result.setResultCode(e.getErrCode());
		} catch (Exception ex) {
			BankLogUtils.printServiceImplExceptionLog(ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E6029);
		}
		return result;
	}

	/**
	 * 银行返回类请求
	 * 
	 * @param BaseMessage
	 * @return Result
	 */
	public Result bankBack(BaseMessage base) {
		Result result = new Result(false);
		try {
			AbcB2bMessage messageB2B = new AbcB2bMessage();
			BeanUtils.copyProperties(base, messageB2B);
			AbcB2bMessage b2b = (AbcB2bMessage) abcB2bManager.verify(messageB2B);
			b2b.setOrderId(b2b.getResOrderNo());
			b2b.setBankOrderId(b2b.getResOrderNo());
			b2b.setAmount(new BigDecimal(b2b.getResAmount()));
			result.setModel("res", b2b);
			result.setDefaultModel(b2b != null ? true : false);
			result.setSuccess(true);
			
			Map<String, String> param = new HashMap<String, String>();
			if((Boolean) result.getDefaultModel()){
				if(b2b.isSuccess()){
					param.put("orderId", b2b.getResOrderNo());
					param.put("amt", b2b.getResAmount());
					param.put("cardType", "Unknown");
					param.put("notifyNum", "1");
					param.put("payStatus", "00");
					param.put("retCode", "00");
					param.put("retMsg", "验签成功");
					param.put("signData", messageB2B.getSignMessage());
					param.put("isFront", String.valueOf(base.isFront()));
					result.setModel("isNotifyCashier", param);
					result.setOrderStatus(true);
				} else {
					// 通知后台地址该订单失败
					param.put("orderId", b2b.getResOrderNo());
					param.put("amt", b2b.getResAmount());
					param.put("cardType", "Unknown");
					param.put("notifyNum", "1");
					param.put("payStatus", "01");
					param.put("retCode", "01");
					param.put("retMsg", "验签失败");
					param.put("signData", messageB2B.getSignMessage());
					param.put("isFront", String.valueOf(base.isFront()));
					result.setModel("isNotifyCashier", param);
					result.setOrderStatus(false);
				}
			  }
		} catch (GopayException e) {
			BankLogUtils.printServiceImplExceptionLog(e);
			result.setResultCode(e.getErrCode());
		} catch (Exception ex) {
			BankLogUtils.printServiceImplExceptionLog(ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E6064);
		}
		return result;
	}

	/**
	 * 银行查询类请求
	 * 
	 * @param BaseMessage
	 * @return Result
	 */
	public Result query(BaseMessage base) {
		Result result = new Result(false);
		try {
			AbcB2bMessage messageB2B = new AbcB2bMessage();
			BeanUtils.copyProperties(base, messageB2B);
			AbcB2bMessage b2b = (AbcB2bMessage) abcB2bManager.query(messageB2B);
			result.setDefaultModel(b2b);
			result.setSuccess(true);
			if(BisPayCheckUtils.checkExternalOrderID(messageB2B.getOrderId())){
				Map<String, String> param = new HashMap<String, String>();
				param.put("orderId", messageB2B.getResOrderNo());
				param.put("amount", messageB2B.getResAmount());
				if (b2b == null) {
					// 查询订单为空
					param.put("returnCode", BisPayConstants.QUERYSTATE_FAIL);
					param.put("returnMessage", "银行返回对账结果为空");
					param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
					result.setModel("queryResult", param);
					return result;
		        }else if (StringUtils.isEmpty(b2b.getOrderStatus())) {
		        	// 查询订单错误
					param.put("returnCode", BisPayConstants.QUERYSTATE_FAIL);
					param.put("returnMessage", b2b.getErrorMessage());
					param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
					result.setModel("queryResult", param);
					return result;
				}else{
					param.put("returnCode", BisPayConstants.QUERYSTATE_SUCCESS);
					if(b2b.getOrderStatus() != null && !b2b.getOrderStatus().equals("")){
					    // 订单状态成功(订单已结算)
                        if (AbcConstants.ABC_ORDERSTATUS_SETTLEMENT_ORDER.equals(b2b.getOrderStatus())) {
                            param.put("tradeState", BisPayConstants.TRADESTATE_SUCCESS);
                            param.put("returnMessage", AbcConstants.ABC_SETTLEMENT_ORDER_MESSAGE);      
                        }
                        // 订单状态暂不处理(订单已建立，等待支付)
                        else if (AbcConstants.ABC_ORDERSTATUS_ESTABLISH.equals(b2b.getOrderStatus())) {
                            param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
                            param.put("returnMessage", AbcConstants.ABC_ESTABLISH_MESSAGE);
                        }
                        // 订单状态暂不处理(订单无回应)
                        else if (AbcConstants.ABC_ORDERSTATUS_CONSUMER_PAID.equals(b2b.getOrderStatus())) {
                            param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
                            param.put("returnMessage", AbcConstants.ABC_CONSUMER_PAID_MESSAGE);
                        }
                        // 订单状态暂不处理(订单已退款)
                        else if (AbcConstants.ABC_ORDERSTATUS_REFUND.equals(b2b.getOrderStatus())) {
                            param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
                            param.put("returnMessage", AbcConstants.ABC_REFUND_MESSAGE);
                        }
                        // 订单状态失败处理(订单已取消)
                        else if (AbcConstants.ABC_ORDERSTATUS_CANCEL.equals(b2b.getOrderStatus())) {
                            //失败处理
                            param.put("tradeState", BisPayConstants.TRADESTATE_FAIL);
                            param.put("returnMessage", AbcConstants.ABC_CANCEL_MESSAGE);
                        }
                        // 订单状态失败处理(订单支付失败）
                        else if (AbcConstants.ABC_ORDERSTATUS_FAILURE.equals(b2b.getOrderStatus())) {
                            param.put("tradeState", BisPayConstants.TRADESTATE_FAIL);
                            param.put("returnMessage", AbcConstants.ABC_FAILURE_MESSAGE);
                        }else{
							param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
							param.put("returnMessage", "交易结果未明确");
		     			}		     			
			        }else{
						param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
						param.put("returnMessage", "银行返回订单未查到");
		            }
				}
				result.setModel("queryResult", param);
			}
		} catch (GopayException e) {
			BankLogUtils.printServiceImplExceptionLog(e);
			result.setResultCode(e.getErrCode());
		} catch (Exception ex) {
			BankLogUtils.printServiceImplExceptionLog(ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E6033);
		}
		return result;
	}

	/**
	 * 银行退款类请求
	 * 
	 * @param BaseMessage
	 * @return Result
	 */
	@Override
	public Result refund(BaseMessage base) {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * 银行日终类请求
	 * 
	 * @param BaseMessage
	 * @return Result
	 */
	@Override
	public Result dayend(BaseMessage base) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Result queryBack(BaseMessage base) {
		// TODO Auto-generated method stub
		return null;
	}

    @Override
    public Result refundBack(BaseMessage base) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Result refundQuery(BaseMessage base) {
        // TODO Auto-generated method stub
        return null;
    }

	@Override
	public Result sendBankRefund(BaseMessage base) {
		// TODO Auto-generated method stub
		return null;
	}

}
